import axios from "axios";
import * as XLSX from 'xlsx'

/*
 * 获取陈列形式（前端用）
 */
export async function api_getFkChenlieType(dataID, showCeng = true, showPaimian = true) {
    const _this = this;
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/TPMActivityAgreementDetailObj/controller/RelatedList";
    let sendData = {
        "associate_object_data_id": dataID,
        "lookup_data_id": dataID,
        "associate_object_describe_api_name": "TPMActivityAgreementObj",
        "associated_object_describe_api_name": "TPMActivityAgreementDetailObj",
        "include_associated": true,
        "search_query_info": "{\"limit\":2000,\"offset\":0,\"filters\":[]}"
    }
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        let typeList = res.data.Value.dataList;
        typeList.forEach((item, index) => {
            ret = ret + item["name"];
            if (showCeng) {
                ret = ret + " " + item["field_ukLIt__c__r"];
            }
            if (showPaimian) {
                ret = ret + " " + item["field_s2Kn1__c"] + "排面";
            }
            ret = ret + ","
        })
        ret = (ret.substring(ret.length - 1) == ',') ? ret.substring(0, ret.length - 1) : ret;
    })
    return ret;
}

/*
 * 获取陈列详情（后端用）
 */
export async function api_getActivityTypeList(dataID, showCeng = true, showPaimian = true) {
    const _this = this;
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/TPMActivityAgreementDetailObj/controller/RelatedList";
    let sendData = {
        "associate_object_data_id": dataID,
        "lookup_data_id": dataID,
        "associate_object_describe_api_name": "TPMActivityAgreementObj",
        "associated_object_describe_api_name": "TPMActivityAgreementDetailObj",
        "include_associated": true,
        "search_query_info": "{\"limit\":2000,\"offset\":0,\"filters\":[]}"
    }
    let ret = [];
    await axios.post(
        url,
        sendData
    ).then((res) => {
        ret = res.data.Value.dataList;
    })
    if (ret.length > 100) {
        ret = [];
    }
    return ret;
}

export async function api_getDaishenpi(month = 3, year = 2022) {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/agreement_proof_summary__c/controller/List";
    let ret = "";
    let sendData = {
        "serializeEmpty": false, "extractExtendInfo": true,
        "object_describe_api_name": "agreement_proof_summary__c",
        "search_template_id": "5d0c806a7cfed91f3e95ba8e", "include_describe": false,
        "search_template_type": "default", "ignore_scene_record_type": true,
        "search_query_info": "{\"limit\":20,\"offset\":0,\"filters\":[{\"field_name\":\"month__c\",\"field_values\":[\"" + month + "\"],\"operator\":\"EQ\",\"filterGroup\":\"1\"},{\"field_name\":\"approval_status__c\",\"field_values\":[\"schedule\"],\"operator\":\"EQ\",\"filterGroup\":\"1\"}],\"orders\":[{\"fieldName\":\"last_modified_time\",\"isAsc\":false}]}"
    }
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getDaishenpi------->", res)
        ret = res;
    })
    return ret;
}

export async function api_getZeroSalesNumber(month = 4, year = 2022) {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/agreement_proof_summary__c/controller/List"
    let sendData = {
        "find_explicit_total_num": true,
        "object_describe_api_name": "agreement_proof_summary__c",
        "search_template_id": "5d0c806a7cfed91f3e95ba8e",
        "include_describe": false,
        "search_template_type": "default",
        "ignore_scene_record_type": true,
        "search_query_info": "{\"limit\":50,\"offset\":0,\"filters\":[{\"field_name\":\"month__c\",\"field_values\":[\"" + month + "\"],\"operator\":\"EQ\",\"filterGroup\":\"1\"},{\"field_name\":\"monthly_sales_count__c\",\"field_values\":[\"\"],\"operator\":\"IS\",\"filterGroup\":\"1\"}],\"orders\":[{\"fieldName\":\"last_modified_time\",\"isAsc\":false}]}"
    }
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getZeroSalesNumber------->", res["data"]["Value"]["total"])
        ret = res;
    })
    return ret["data"]["Value"]["total"];
}

/*
 * 根据网点编码搜索网点信息
 */
export async function api_getShopDetailsByShopCode(shopCode = "") {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/AccountObj/controller/List";
    let sendData = {
        "serializeEmpty": false,
        "extractExtendInfo": true,
        "object_describe_api_name": "AccountObj",
        "search_template_id": "5d0c75f37cfed94d92c8db42",
        "include_describe": false,
        "search_template_type": "default",
        "ignore_scene_record_type": false,
        "search_query_info": "{\"limit\":50,\"offset\":0,\"filters\":[{\"field_name\":\"account_no\",\"field_values\":[\"" + shopCode + "\"],\"operator\":\"LIKE\"}],\"orders\":[{\"fieldName\":\"last_modified_time\",\"isAsc\":false}]}"
    }
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getShopDetailsByShopCode------->", res["data"]["Value"]["dataList"])
        ret = res;
    })
    if (ret["data"]["Value"]["dataList"].length > 0) {
        return ret["data"]["Value"]["dataList"][0]
    } else {
        return []
    }
}

/*
 * 根据网点ID获取网点详情
 */
export async function api_getShopDetailsByShopID(_id = "") {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/AccountObj/controller/WebDetail";
    let sendData = {
        "layoutVersion": "V3",
        "objectDataId": _id,
        "objectDescribeApiName": "AccountObj",
        "fromRecycleBin": false,
        "management": false,
        "serializeEmpty": false,
        "describeVersionMap": {"AccountObj": 1221}
    }
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getShopDetailsByShopID------->", _id, res["data"]["Value"]["data"])
        ret = res["data"]["Value"]["data"];
    })
    return ret;
}

/*
 * 根据网点编码和月份获取活动检核详情
 */
export async function api_getFeeDetailsByShopCodeAndMonth(shopCode = "", month = "4") {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/agreement_proof_summary__c/controller/List";
    let query = {
        "limit": 100,
        "offset": 0,
        "filters": [{
            "field_name": "month__c",
            "field_values": [month],
            "operator": "EQ",
            "filterGroup": "1"
        }, {"field_name": "account_no__c", "field_values": [shopCode], "operator": "EQ", "filterGroup": "1"}],
        "orders": [{"fieldName": "activity_agreement_id__c.name", "isAsc": false}]
    }
    let sendData = {
        "serializeEmpty": false,
        "extractExtendInfo": true,
        "object_describe_api_name": "agreement_proof_summary__c",
        "include_describe": false,
        "search_template_type": "default",
        "ignore_scene_record_type": true,
        "search_query_info": JSON.stringify(query)
    }
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getFeeDetailsByShopCodeAndMonth------->", res["data"]["Value"]["dataList"])
        ret = res;
    })
    if (ret["data"]["Value"]["dataList"].length > 0) {
        return ret["data"]["Value"]["dataList"][0]
    } else {
        return []
    }
}

export async function api_getSearchTourPhotoByShopID(shopID = "", apiName = "") {
    let url = "https://www.fxiaoke.com/FHH/EM1HFEED/Feeds/searchFeedResourceList"
    let sendData = {
        "resourceId": apiName + "|" + shopID,
        "limit": 1000
    }
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getSearchTourPhotoByShopID------->", res["data"]["Value"]["feedList"])
        ret = res;
    })
    return ret["data"]["Value"]["feedList"]
}

/*
 * 获取同事列表
 */
export async function api_getEmployeeList() {
    let url = "https://www.fxiaoke.com/FHH/EM1HORGBIZ/Organization/getByVersion";
    let sendData = {"localVersion": 0}
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getEmploeeList------->", res["data"]["Value"]["employees"])
        ret = res;
    })
    return ret["data"]["Value"]["employees"];
}

/*
 * 获取key名称
 */
export async function api_getAPIKeyDict() {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/CheckinsObj/controller/ListHeader"
    let sendData = {"include_layout": true, "layout_type": "list", "list_type": "list"}
    let ret = "";
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getAPIKeyDict------->", res["data"]["Value"]["objectDescribe"]["fields"])
        ret = res;
    })
    return ret["data"]["Value"]["objectDescribe"]["fields"];
}

/*
 * 获取筛选后的巡店照片（时间+员工ID）
 */
export async function api_getCheckInSearchResult(employeeID = "", shopCode = "", start = 0, end = 0, page = 1, size = 10) {
    if (start == 0) {
        end = Math.round(new Date())
    } else {
        end = end + 86400000
    }
    let query_info = {
        "limit": size,
        "offset": (page - 1) * size,
        "filters": [
            {
                "field_name": "doorphoto__c", "field_values": [""], "operator": "ISN"
            }, {
                "field_name": "create_time", "field_values": [start, end], "operator": "BETWEEN"
            }
        ],
        "orders": [{"fieldName": "last_modified_time", "isAsc": false}]
    }
    if (employeeID != "") {
        query_info.filters.push({
            "field_name": "created_by",
            "field_values": ["{\"employee\":[\"" + employeeID + "\"]}"],
            "operator": "IN",
            "value_type": 5
        })
    }
    if (shopCode != "") {
        query_info.filters.push({
            "field_name": "field_z02bG__c",
            "field_values": [shopCode],
            "operator": "EQ"
        })
    }
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/CheckinsObj/controller/List"
    let sendData = {
        "serializeEmpty": false,
        "extractExtendInfo": true,
        "object_describe_api_name": "CheckinsObj",
        "search_template_id": "5d0c806a7cfed91f3e95ba8e",
        "include_describe": false,
        "search_template_type": "default",
        "ignore_scene_record_type": true,
        "search_query_info": JSON.stringify(query_info)
    }
    let picList = [];
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getCheckInSearchResult------->", res["data"]["Value"]["dataList"])
        let tmpList = res["data"]["Value"]["dataList"];
        tmpList.forEach((dataItem, dataIndex) => {
            let keyList = Object.keys(dataItem);
            let shopCode__c = dataItem["shopCode__c"]
            keyList.forEach((keyItem, keyIndex) => {
                if (keyItem == "image_path") {
                    try {
                        dataItem[keyItem].forEach((a, b) => {
                            dataItem[keyItem][b]["shopCode__c"] = shopCode__c;
                        })
                        picList = picList.concat(dataItem[keyItem])
                    } catch (e) {
                        console.log(apiKeyDict[keyItem], keyItem, dataItem[keyItem]);
                    }
                }
            })
        })
    })

    return picList;
}

/*
 * 获取业代网点列表
 */
export async function api_getClientList(employeeID = "", dealerName = "", page = 1, size = 20) {
    console.log("input_dealerName------>", dealerName, employeeID);
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/AccountObj/controller/List";
    let query_info = {
        "limit": size,
        "offset": (page - 1) * size,
        "filters": [{
            "field_name": "life_status",
            "field_values": ["normal"],
            "operator": "EQ",
            "filterGroup": "1"
        }, {
            "field_name": "sign_state__c",
            "field_values": ["1"],
            "operator": "EQ",
            "filterGroup": "1"
        }],
        "orders": [{"fieldName": "last_modified_time", "isAsc": false}]
    }
    if (employeeID != "") {
        query_info.filters.push({
            "field_name": "owner",
            "field_values": ["{\"employee\":[\"" + employeeID + "\"]}"],
            "operator": "IN",
            "value_type": 5
        })
    }
    if (dealerName != "") {
        query_info.filters.push({
            "field_name": "dealer_id.name",
            "field_values": [dealerName],
            "operator": "LIKE",
            "filterGroup": "1"
        })
    } else {
        query_info.filters.push({
            "field_name": "dealer_id.name",
            "field_values": [""],
            "operator": "ISN",
            "filterGroup": "1"
        })
    }
    let sendData = {
        "serializeEmpty": false,
        "extractExtendInfo": true,
        "object_describe_api_name": "AccountObj",
        "search_template_id": "5d0c75f37cfed94d92c8db42",
        "include_describe": false,
        "search_template_type": "default",
        "ignore_scene_record_type": true,
        "search_query_info": JSON.stringify(query_info)
    }
    let ret = [];
    let total = 0;
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getClientList------->", res["data"]["Value"]["dataList"])
        ret = res["data"]["Value"]["dataList"];
        total = res["data"]["Value"]["total"];
    })
    if (total > 10000) {
        return false;
    }
    return ret;
}

/*
 * 检核重审
 * @ 陈列是否达标
 * @ 人工调解发放像是
 * @ 检核意见
 * 返回值： 失败：-1 成功：0
 */
export async function api_sendFeeVerify(objectDataId = "", is_verify = false, verify_num = 0, verify_mark = "") {
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/agreement_proof_summary__c/action/button_1k9vY__c";
    if (objectDataId == "") {
        return -1;
    }
    let sendData = {
        "objectDataId": objectDataId,
        "args": {
            "form_qualified__c": is_verify.toString(),
            "form_monthly_fee_box_artificial_count__c": verify_num.toString(),
            "form_field_y1vt9__c": verify_mark,
            "form_qualified__c__o": "",
            "qualified__c__o": ""
        }
    }
    let retCode = -1;
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_sendFeeVerify------->", res["data"]["Result"]["FailureCode"])
        retCode = res["data"]["Result"]["FailureCode"];
    })
    return retCode;
}
export async function api_chenlieShenpi(id, form_application_form_id__c,form_year__c,form_month__c){
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/agreement_proof_summary__c/action/button_j4O5s__c";
    let sendData = {
        "objectDataId": id,
        "args": {
            "form_application_form_id__c": form_application_form_id__c,
            "form_year__c": form_year__c.toString(),
            "form_month__c": form_month__c.toString()
        }
    }
    let retCode = -1;
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_chenlieShenpi------->", res["data"]["Result"]["FailureCode"])
        retCode = res["data"]["Result"]["FailureCode"];
    })
    return retCode;
}
/*
 * 获取陈列待审批列表
 */
export async function api_getShenpiList(year=2022, month=4){
    let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/agreement_proof_summary__c/controller/List"
    let sendData = {
        "serializeEmpty": false, "extractExtendInfo": true,
        "object_describe_api_name": "agreement_proof_summary__c",
        "search_template_id": "5d0c806a7cfed91f3e95ba8e", "include_describe": false,
        "search_template_type": "default", "ignore_scene_record_type": true,
        "search_query_info": "{\"limit\":20,\"offset\":0,\"filters\":[{\"field_name\":\"month__c\",\"field_values\":["+ month.toString() +"],\"operator\":\"EQ\",\"filterGroup\":\"1\"},{\"field_name\":\"approval_status__c\",\"field_values\":[\"schedule\"],\"operator\":\"EQ\",\"filterGroup\":\"1\"}],\"orders\":[{\"fieldName\":\"last_modified_time\",\"isAsc\":false}]}"
    }
    let dataList = [];
    let total = 0;
    await axios.post(
        url,
        sendData
    ).then((res) => {
        console.log("api_getShenpiItem------->", res["data"])
        dataList = res["data"]["Value"]["dataList"]
        total = res["data"]["Value"]["total"]
    })
    return {
        dataList,total
    };
}

export default class fxxkAPI {
    constructor() {
        this.app_id = "cli_a16882208fb8500c"
        this.downUrl = "https://www.fxiaoke.com/FSC/EM/File/DownloadByPath?path="
        this.downloadUrl = undefined
    }

    /*
     *
     */
    async getSearchList(apiName = "", query={}) {
        let dataList = [];
        let total = 0;
        if(apiName == ""){
            return {dataList,total};
        }
        let url = "https://www.fxiaoke.com/FHH/EM1HNCRM/API/v1/object/" + apiName + "/controller/List"
        let sendData = {
            "serializeEmpty": false,
            "extractExtendInfo": true,
            "object_describe_api_name": apiName,
            "include_describe": false,
            "search_template_type": "custom",
            "ignore_scene_filter": true,
            "ignore_scene_record_type": true,
            "search_query_info": JSON.stringify(query)
        }
        await axios.post(
            url,
            sendData
        ).then((res) => {
            console.log("getSearchList----->",apiName,"----->", res["data"]["Value"]["dataList"])
            dataList = res["data"]["Value"]["dataList"];
            total = res["data"]["Value"]["total"];
        })
        return {dataList,total};

    }

    /*
     * 创建导出任务
     * @ sendData:任务数据
     * @ 返回:创建成功的任务ID
     */
    async api_createExportMission(sendData = "") {
        let url = "https://www.fxiaoke.com/FHH/EM1HJobCenter/inputJobCenter/createJob";
        let retId = "";
        await axios.post(
            url,
            sendData
        ).then((res) => {
            console.log("api_createExportMission------->", res["data"]["Value"]["id"])
            retId = res["data"]["Value"]["id"];
        })
        return retId;
    }

    async api_exportFile(id = "", apiName = "") {
        let query = {}
        let sendData = {
            "apiName": apiName, "templateId": "crm_002",
            "queryParam": {
                "object_describe_api_name": apiName,
                "search_template_id": id,
                "include_describe": false,
                "search_template_type": "default",
                "ignore_scene_record_type": false,
                "search_query_info": query,
                "according_to_list": true,
                "no_export_relevant_team": true
            },
            "jobType": 2
        }
        let jobId = "";
        await this.api_createExportMission(sendData).then(retId => {
            jobId = retId;
        })
        console.log("创建导出文件任务-------->", jobId);
        return jobId;
    }

    /*
     * 获取任务导出状态
     * @ 成功返回url 失败返回空
     */
    async api_getExportMissionStatus(jobId) {
        let url = "https://www.fxiaoke.com/FHH/EM1HJobCenter/inputJobCenter/queryJobState"
        let sendData = {
            "jobId": jobId
        }
        let ret = ""
        await axios.post(
            url,
            sendData
        ).then((res) => {
            console.log("api_getExportMissionStatus------->", res["data"]["Value"]["id"])
            ret = res;
        })
        try {
            return ret["data"]["Value"]["url"]
        } catch (e) {
            return ""
        }
    }

    /*
     * 读取xlxs
     */
    async downloadFileFromUrl(url = "") {
        let blob = null;
        await axios.get(url, {
            responseType: "blob",
            headers: {
                "Accept": "application/octet-stream",
                "Access-Control-Expose-Headers": "Content-Disposition"
            }
        }).then(res => {
            blob = new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
            });
        })
        const dataBinary = await this.readFile(blob)
        const workBook = XLSX.read(dataBinary, {
            type: 'binary',
            cellDates: true
        })
        const workSheet = workBook.Sheets[workBook.SheetNames[0]]
        const data = this.sheet2arr(workSheet);
        return data;
    }

    /* 读取文件 */
    readFile(file) {
        return new Promise((resolve) => {
            const reader = new FileReader()
            reader.readAsBinaryString(file)
            reader.onload = (ev) => {
                resolve(ev.target.result)
            }
        })
    }

    /*
     * 清洗数据
     */
    cleanData(dataRaw) {
        dataRaw.forEach((data, dataIndex) => {
            data.forEach((item, itemIndex) => {
                if (!isNaN(this.date2int(item))) {
                    dataRaw[dataIndex][itemIndex] = this.date2int(item)
                }
                // try {
                //     dataRaw[dataIndex][itemIndex] = this.dateHM2num(item)
                // }catch (e) {
                //     dataRaw[dataIndex][itemIndex] = dataRaw[dataIndex][itemIndex]
                // }
                if (this.isNumber(item)) {
                    if (item.indexOf(",") != -1) {
                        item = this.moneyDelete(item);
                    }
                    dataRaw[dataIndex][itemIndex] = parseFloat(item)
                }
            })
        })
        return dataRaw
    }

    /* 日期转换为数字 YY:MM:DD */
    date2int(timeString = "2022-05-08") {
        let date = new Date(timeString)
        return date.getTime() / 86400 / 1000 + 25569 + 0.333333333;
    }

    /* 判断是否为数字 */
    isNumber(val) {
        var reg = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/
        if (val.indexOf(",") != -1) {
            val = this.moneyDelete(val);
        }
        if (val.indexOf("-") != -1 || val.indexOf(":") != -1) {
            return false;
        }
        if (!reg.test(val)) {
            return false;
        } else {
            return true;
        }
    }

    /* 去掉千分位 */
    moneyDelete(num) {
        if (num && num != undefined && num != null) {
            let _num = num;
            _num = _num.toString();
            _num = _num.replace(/,/gi, '');
            return _num
        } else {
            return num
        }
    }

    /* 读取为数组 */
    sheet2arr(sheet) {
        var result = [];
        var row;
        var rowNum;
        var colNum;
        var range = XLSX.utils.decode_range(sheet['!ref']);
        for (rowNum = range.s.r; rowNum <= range.e.r; rowNum++) {
            row = [];
            for (colNum = range.s.c; colNum <= range.e.c; colNum++) {
                var nextCell = sheet[
                    XLSX.utils.encode_cell({r: rowNum, c: colNum})
                    ];
                if (typeof nextCell === 'undefined') {
                    row.push(void 0);
                } else row.push(nextCell.w);
            }
            result.push(row);
        }
        return result;
    };

}
